package com.androwit.engine.cassandra;

import me.prettyprint.cassandra.model.BasicColumnDefinition;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Serializer;
import me.prettyprint.hector.api.ddl.ColumnIndexType;
import me.prettyprint.hector.api.ddl.ComparatorType;

import com.androwit.engine.mapping.BasicMappingField;
import com.androwit.engine.mapping.Converter;

public class HectorMappingField<J, K, V> extends BasicMappingField<J, K, V> {

	protected Serializer<K> keySerializer;
	protected Serializer<V> valueSerializer;
	protected ComparatorType secondaryIndexValidator;
	boolean secondaryIndex;

	public HectorMappingField(K key, Converter<J, V> converter, String name,
			ComparatorType secondaryIndexValidator,
			boolean includeSecondaryIndex) {
		super(key, converter, name);
		if (secondaryIndexValidator == null)
			throw new IllegalArgumentException("validator can't be null");

		this.secondaryIndexValidator = secondaryIndexValidator;
		this.secondaryIndex = includeSecondaryIndex;
	}

	public HectorMappingField(K key, Converter<J, V> converter, String name,
			Serializer<K> keySerializer, Serializer<V> valueSerializer,
			ComparatorType secondaryIndexValidator,
			boolean includeSecondaryIndex) {
		super(key, converter, name);
		if (secondaryIndexValidator == null)
			throw new IllegalArgumentException("validator of key " + key
					+ " can't be null");

		this.secondaryIndexValidator = secondaryIndexValidator;
		this.secondaryIndex = includeSecondaryIndex;
		this.keySerializer = keySerializer;
		this.valueSerializer = valueSerializer;
	}

	public Serializer<K> getKeySerializer() {
		return keySerializer;
	}

	public void setKeySerializer(Serializer<K> keySerializer) {
		this.keySerializer = keySerializer;
	}

	public Serializer<V> getValueSerializer() {
		return valueSerializer;
	}

	public void setValueSerializer(Serializer<V> valueSerializer) {
		this.valueSerializer = valueSerializer;
	}

	public BasicColumnDefinition getColumnDefinition(String columnFamily) {
		BasicColumnDefinition toReturn = new BasicColumnDefinition();
		toReturn.setName(StringSerializer.get().toByteBuffer(key.toString()));
		if (secondaryIndex) {
			toReturn.setIndexType(ColumnIndexType.KEYS);
			toReturn.setIndexName(columnFamily + "_" + key + "_INDEX");
		}
		toReturn.setValidationClass(secondaryIndexValidator.getClassName());

		return toReturn;
	}

	@SuppressWarnings("rawtypes")
	public BasicColumnDefinition getColumnDefinition(
			HectorMappingFieldsDefiner columnFamilyDefinition) {
		return getColumnDefinition(columnFamilyDefinition.getColumnFamily());
	}

	public boolean isSecondaryIndex() {
		return secondaryIndex;
	}

	public void setSecondaryIndex(boolean includeSecondaryIndex) {
		this.secondaryIndex = includeSecondaryIndex;
	}

}
